import Message from './Message'
import eventbus from '../../../services/eventbus'
import { useEffect, useRef, useState } from 'react'
import { IMessage } from './Message/IMessage'
import dayjs from 'dayjs'
import ioService from '../../../services/ioService'

export default () => {
    const [messages, setMessages] = useState<IMessage[]>([])
    const ref = useRef<HTMLDivElement>(null)

    useEffect(() => {
        ref.current.scrollTop = ref.current.scrollHeight
    })

    const onSelfMessage = (message: string) => {
        setMessages(messages => [...messages, {
            name: '我',
            message,
            time: dayjs().format('HH:mm:ss')
        }])
    }
    const onMessage = ({ message, userName }) => {
        setMessages(messages => [...messages, {
            name: userName,
            message,
            time: dayjs().format('HH:mm:ss')
        }])
    }
    useEffect(() => {
        eventbus.on('selfMessage', onSelfMessage);
        ioService.on('message', onMessage)
        return () => {
            eventbus.off('selfMessage', onSelfMessage);
            ioService.off('message', onMessage)
        }
    }, [])

    return <div className="message-list" ref={ref}>
        {messages.map((item, index) => <Message key={index} {...item} />)}
    </div>
}